<template>
  <div class="comment-container">
    <h1 class="title">读者留言</h1>

    <!-- 留言表单 -->
    <div class="comment-form">
      <textarea v-model="newComment" placeholder="留下您的宝贵意见..." class="input-box" :disabled="isSubmitting"></textarea>
      <button @click="submitComment" class="submit-btn" :disabled="isSubmitting">
        {{ isSubmitting ? '提交中...' : '发表留言' }}
      </button>
    </div>

    <!-- 留言列表 -->
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-card">
        <div class="comment-content">{{ comment.message }}</div>
        <div class="comment-meta">
          <span class="comment-time">{{ formatTime(comment.timestamp) }}</span>
        </div>
      </div>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="isLoading" class="loading-indicator">
      <div class="spinner"></div>
      正在加载更多留言...
    </div>
    <div v-if="!hasMore" class="no-more">
      ⭐️ 已经到底啦~
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { throttle } from 'lodash-es'

const { proxy } = getCurrentInstance()

// 响应式数据
const newComment = ref('')
const isSubmitting = ref(false)
const errorMessage = ref('')
const comments = ref([])

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const isLoading = ref(false)
const hasMore = ref(true)

// 新增请求控制变量
let currentRequestId = 0
const lastLoadedPage = ref(1)

// 优化后的加载方法
const loadComments = async (reset = false) => {
  if (isLoading.value || !hasMore.value) return

  const requestId = ++currentRequestId
  isLoading.value = true
  errorMessage.value = ''

  try {
    const targetPage = reset ? 1 : currentPage.value
    lastLoadedPage.value = targetPage

    if (reset) {
      currentPage.value = 1
    } else {
      currentPage.value++ // 关键修改：每次加载新数据时页码+1
    }

    const { data } = await proxy.$axios.post('/api/messages/page', {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    // 直接替换数据（不再保留临时留言）
    if (reset) {
      comments.value = data.records
      currentPage.value = 1
    } else {
      comments.value = [...comments.value, ...data.records]
    }

    totalPages.value = data.pages
    hasMore.value = currentPage.value <= data.pages
  } catch (error) {
    errorMessage.value = error.response?.data?.message || '留言加载失败，请稍后再试'
    ElMessage.error(errorMessage.value)
  } finally {
    isLoading.value = false
  }
}

// 提交留言逻辑（简化版）
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('留言内容不能为空')
    return
  }

  isSubmitting.value = true
  errorMessage.value = ''

  try {
    // 提交留言
    const { data: result } = await proxy.$axios.post('/api/messages/save', {
      message: newComment.value.trim()
    })

    // 显示成功提示
    ElMessage.success(result.message || '留言提交成功')

    // 清空输入框
    newComment.value = ''

    // 强制刷新列表
    await loadComments(true)
    
  } catch (error) {
    errorMessage.value = error.response?.data?.message || '留言提交失败，请稍后再试'
    ElMessage.error(errorMessage.value)
  } finally {
    isSubmitting.value = false
  }
}

// 滚动处理
const handleScroll = throttle(() => {
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement
  const isNearBottom = scrollTop + clientHeight >= scrollHeight - 500

  if (isNearBottom && hasMore.value && !isLoading.value) {
    loadComments()
  }
}, 500)

// 时间格式化
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm')
}

// 生命周期
onMounted(() => {
  loadComments(true)
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  handleScroll.cancel()
})
</script>

<!-- 样式部分保持不变 -->
<style scoped>
/* 原有样式保持不变 */
</style>

<style scoped>
.comment-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: linear-gradient(145deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 2rem;
  font-size: 2.5rem;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.comment-form {
  margin-bottom: 2rem;
}

.input-box {
  width: 100%;
  height: 120px;
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  resize: vertical;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.input-box:focus {
  border-color: #3498db;
  box-shadow: 0 0 8px rgba(52, 152, 219, 0.2);
  outline: none;
}

.submit-btn {
  display: block;
  margin: 1rem auto 0;
  padding: 0.8rem 2rem;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(41, 128, 185, 0.3);
}

.submit-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.comment-list {
  display: grid;
  gap: 1.5rem;
}

.comment-card {
  background: white;
  padding: 1.5rem;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.comment-card:hover {
  transform: translateY(-3px);
}

.comment-content {
  color: #34495e;
  line-height: 1.6;
  font-size: 1.05rem;
}

.comment-meta {
  margin-top: 1rem;
  display: flex;
  justify-content: flex-end;
}

.comment-time {
  color: #7f8c8d;
  font-size: 0.9rem;
}

.error-message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 1rem 2rem;
  background: #e74c3c;
  color: white;
  border-radius: 8px;
  animation: slideIn 0.3s ease;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 1.5rem;
  color: #7f8c8d;
}

.no-more {
  text-align: center;
  padding: 2rem;
  color: #95a5a6;
  font-size: 0.9rem;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
  }

  to {
    transform: translateX(0);
  }
}

@media (max-width: 768px) {
  .comment-container {
    margin: 1rem;
    padding: 1.5rem;
  }

  .title {
    font-size: 2rem;
  }

  .comment-card {
    padding: 1rem;
  }
}
</style>